<template>
  <div class="health-data-form">
    <h2>健康数据录入</h2>
    
    <form @submit.prevent="handleSubmit">
      <!-- 四方格布局容器 -->
      <div class="grid-container">
        <!-- 1. 基本信息卡片 -->
        <div class="form-card">
          <div class="form-section">
            <h3>基本信息</h3>
            <div class="form-group">
              <label for="age">年龄 *</label>
              <input 
                type="number" 
                v-model.number="healthData.age" 
                id="age" 
                placeholder="请输入您的年龄" 
                required 
              />
              <span v-if="ageError" class="error">{{ ageError }}</span>
            </div>
            <div class="form-group">
              <label for="gender">性别 *</label>
              <select v-model.number="healthData.gender" id="gender" required>
                <option value="">请选择</option>
                <option value="1">男</option>
                <option value="2">女</option>
              </select>
            </div>
          </div>
        </div>

        <!-- 2. 身体指标卡片 -->
        <div class="form-card">
          <div class="form-section">
            <h3>身体指标</h3>
            <div class="form-group">
              <label for="height">身高 (cm) *</label>
              <input 
                type="number" 
                v-model.number="healthData.height" 
                id="height" 
                placeholder="请输入100-250之间的身高" 
                required 
              />
              <span v-if="heightError" class="error">{{ heightError }}</span>
            </div>
            <div class="form-group">
              <label for="weight">体重 (kg) *</label>
              <input 
                type="number" 
                v-model.number="healthData.weight" 
                id="weight" 
                placeholder="请输入30-200之间的体重" 
                required 
              />
              <span v-if="weightError" class="error">{{ weightError }}</span>
            </div>
            <!-- 计算结果展示 -->
            <div class="calculated-info" v-if="showCalculatedInfo">
              <p>BMI: {{ calculatedBMI }} ({{ bmiCategory }})</p>
              <p>年龄分组: {{ ageGroup }}</p>
            </div>
          </div>
        </div>

        <!-- 3. 医疗指标卡片 -->
        <div class="form-card">
          <div class="form-section">
            <h3>医疗指标</h3>
            <div class="form-group">
              <label for="apHi">血压-高值 (mmHg) *</label>
              <input 
                type="number" 
                v-model.number="healthData.apHi" 
                id="apHi" 
                placeholder="请输入收缩压" 
                required 
              />
              <span v-if="apHiError" class="error">{{ apHiError }}</span>
            </div>
            <div class="form-group">
              <label for="apLo">血压-低值 (mmHg) *</label>
              <input 
                type="number" 
                v-model.number="healthData.apLo" 
                id="apLo" 
                placeholder="请输入舒张压" 
                required 
              />
              <span v-if="apLoError" class="error">{{ apLoError }}</span>
            </div>
            <div class="form-group">
              <label for="cholesterol">胆固醇 *</label>
              <select v-model.number="healthData.cholesterol" id="cholesterol" required>
                <option value="">请选择</option>
                <option value="1">正常</option>
                <option value="2">偏高</option>
                <option value="3">很高</option>
              </select>
            </div>
            <div class="form-group">
              <label for="gluc">葡萄糖 *</label>
              <select v-model.number="healthData.gluc" id="gluc" required>
                <option value="">请选择</option>
                <option value="1">正常</option>
                <option value="2">偏高</option>
                <option value="3">很高</option>
              </select>
            </div>
          </div>
        </div>

        <!-- 4. 生活习惯卡片 -->
        <div class="form-card">
          <div class="form-section">
            <h3>生活习惯</h3>
            <div class="form-group">
              <label for="smoke">抽烟</label>
              <select v-model.number="healthData.smoke" id="smoke">
                <option value="0">否</option>
                <option value="1">是</option>
              </select>
            </div>
            <div class="form-group">
              <label for="alco">饮酒</label>
              <select v-model.number="healthData.alco" id="alco">
                <option value="0">否</option>
                <option value="1">是</option>
              </select>
            </div>
            <div class="form-group">
              <label for="active">积极运动</label>
              <select v-model.number="healthData.active" id="active">
                <option value="0">否</option>
                <option value="1">是</option>
              </select>
            </div>
            <div class="form-group">
              <label for="cardio">有氧运动</label>
              <select v-model.number="healthData.cardio" id="cardio">
                <option value="0">否</option>
                <option value="1">是</option>
              </select>
            </div>
          </div>
        </div>
      </div>

      <!-- 提交区域 -->
      <div class="submit-section">
        <button 
          type="submit" 
          class="submit-btn" 
          :disabled="isSubmitting"
        >
          {{ isSubmitting ? '提交中...' : '提交数据' }}
        </button>
      </div>
    </form>
  </div>
</template>

<script>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import fastApi from '../../utils/fastApiConfig'
import { syncPredictionToWindowsDB } from '../../utils/dataSyncService'

export default {
  name: 'HealthDataForm',
  setup() {
    const router = useRouter()
    // 表单基础数据
    const healthData = ref({
      age: '',
      gender: '',
      height: '',
      weight: '',
      apHi: '',
      apLo: '',
      cholesterol: '',
      gluc: '',
      smoke: 0,
      alco: 0,
      active: 0,
      cardio: 0,
      userId: 0,
      indicatorId: 0,
      bmi: 0,
      bmiCat: '',
      ageGroup: '',
      isAbnormal: 0,
      submitTime: new Date(),
      updateTime: new Date()
    })

    // 状态管理
    const ageError = ref('')
    const heightError = ref('')
    const weightError = ref('')
    const apHiError = ref('')
    const apLoError = ref('')
    const isSubmitting = ref(false)

    // 计算属性
    const calculatedBMI = computed(() => {
      if (healthData.value.height && healthData.value.weight) {
        const heightInM = healthData.value.height / 100
        const bmi = healthData.value.weight / (heightInM * heightInM)
        return bmi.toFixed(1)
      }
      return ''
    })

    const bmiCategory = computed(() => {
      const bmi = parseFloat(calculatedBMI.value)
      if (isNaN(bmi)) return ''
      if (bmi < 18.5) return '偏瘦'
      if (bmi < 24) return '正常'
      if (bmi < 28) return '超重'
      return '肥胖'
    })

    const ageGroup = computed(() => {
      const age = healthData.value.age
      if (!age) return ''
      if (age >= 18 && age <= 30) return '18-30岁'
      if (age <= 45) return '31-45岁'
      if (age <= 60) return '46-60岁'
      return '60岁以上'
    })

    const showCalculatedInfo = computed(() => {
      return !!healthData.value.age && !!healthData.value.height && !!healthData.value.weight
    })

    // 表单验证
    const validateForm = () => {
      let isValid = true
      // 年龄验证
      if (!healthData.value.age) {
        ageError.value = '请输入年龄'
        isValid = false
      } else if (healthData.value.age < 18 || healthData.value.age > 120) {
        ageError.value = '年龄需在18-120岁之间'
        isValid = false
      } else {
        ageError.value = ''
      }

      // 身高验证
      if (!healthData.value.height) {
        heightError.value = '请输入身高'
        isValid = false
      } else if (healthData.value.height < 100 || healthData.value.height > 250) {
        heightError.value = '身高需在100-250cm之间'
        isValid = false
      } else {
        heightError.value = ''
      }

      // 体重验证
      if (!healthData.value.weight) {
        weightError.value = '请输入体重'
        isValid = false
      } else if (healthData.value.weight < 30 || healthData.value.weight > 200) {
        weightError.value = '体重需在30-200kg之间'
        isValid = false
      } else {
        weightError.value = ''
      }

      // 血压高值验证
      if (!healthData.value.apHi) {
        apHiError.value = '请输入收缩压'
        isValid = false
      } else if (healthData.value.apHi < 90 || healthData.value.apHi > 180) {
        apHiError.value = '收缩压需在90-180mmHg之间'
        isValid = false
      } else {
        apHiError.value = ''
      }

      // 血压低值验证
      if (!healthData.value.apLo) {
        apLoError.value = '请输入舒张压'
        isValid = false
      } else if (healthData.value.apLo < 60 || healthData.value.apLo > 120) {
        apLoError.value = '舒张压需在60-120mmHg之间'
        isValid = false
      } else {
        apLoError.value = ''
      }

      return isValid
    }

    // 提交处理
    const handleSubmit = async () => {
      if (!validateForm()) return

      const submitData = {
        ...healthData.value,
        bmi: parseFloat(calculatedBMI.value) || 0,
        bmiCat: bmiCategory.value,
        ageGroup: ageGroup.value,
        isAbnormal: (
          (healthData.value.apHi < 90 || healthData.value.apHi > 140 || 
           healthData.value.apLo < 60 || healthData.value.apLo > 90) ||
          healthData.value.cholesterol > 1 ||
          healthData.value.gluc > 1
        ) ? 1 : 0,
        submitTime: new Date(),
        updateTime: new Date()
      }

      try {
        // 从localStorage获取用户信息
        let userId = null;
        
        try {
          // 添加详细调试日志
          console.log('localStorage中的所有键:', Object.keys(localStorage));
          
          // 放宽登录状态检查，不依赖userLoggedIn标志
          // 尝试获取用户ID的多种可能方式
          
          // 方式1: 直接尝试获取userInfo
          const userInfoStr = localStorage.getItem('userInfo');
          console.log('userInfo字符串:', userInfoStr);
          
          if (userInfoStr) {
            try {
              const userInfo = JSON.parse(userInfoStr);
              console.log('解析后的userInfo对象:', userInfo);
              
              // 尝试从多种可能的字段名中获取用户ID
              const possibleIdFields = ['userId', 'id', 'user_id'];
              
              for (const field of possibleIdFields) {
                if (userInfo[field] && !isNaN(parseInt(userInfo[field]))) {
                  userId = parseInt(userInfo[field]);
                  console.log('从字段', field, '获取到用户ID:', userId);
                  break;
                }
              }
              
              // 如果在userInfo根对象中没找到，尝试在嵌套对象中查找
              if (!userId && userInfo.data && userInfo.data.id) {
                userId = parseInt(userInfo.data.id);
                console.log('从data.id获取到用户ID:', userId);
              }
              
              // 尝试其他可能的嵌套路径
              if (!userId && userInfo.data && userInfo.data.userId) {
                userId = parseInt(userInfo.data.userId);
                console.log('从data.userId获取到用户ID:', userId);
              }
              
              // 尝试其他可能的嵌套路径
              if (!userId && userInfo.userInfo && userInfo.userInfo.userId) {
                userId = parseInt(userInfo.userInfo.userId);
                console.log('从userInfo.userInfo.userId获取到用户ID:', userId);
              }
              
              // 也检查userInfo.userInfo.id路径
              if (!userId && userInfo.userInfo && userInfo.userInfo.id) {
                userId = parseInt(userInfo.userInfo.id);
                console.log('从userInfo.userInfo.id获取到用户ID:', userId);
              }
            } catch (parseError) {
              console.error('解析userInfo时出错:', parseError);
            }
          }
          
          // 方式2: 尝试直接获取userId键
          if (!userId) {
            const directUserId = localStorage.getItem('userId');
            if (directUserId && !isNaN(parseInt(directUserId))) {
              userId = parseInt(directUserId);
              console.log('从localStorage直接键userId获取到用户ID:', userId);
            }
          }
          
          // 方式3: 尝试获取id键
          if (!userId) {
            const directId = localStorage.getItem('id');
            if (directId && !isNaN(parseInt(directId))) {
              userId = parseInt(directId);
              console.log('从localStorage直接键id获取到用户ID:', userId);
            }
          }
        } catch (e) {
          console.error('获取用户信息时出错:', e);
        }
        
        // 如果未能获取到用户ID，显示错误并跳转登录
        if (!userId || isNaN(userId)) {
          alert('用户信息无效，请先登录后再提交数据');
          router.push('/login');
          return;
        }
        
        submitData.userId = userId
        
        isSubmitting.value = true
        // 1. 先提交到SpringBoot保存到MySQL
        const response = await axios.post('http://localhost:8080/api/health-indicator/add', submitData)
        
        if (response.data > 0) {
          // 2. 然后发送数据到FastAPI模型进行预测
          try {
            // 转换数据格式以匹配FastAPI所需字段
            const fastApiData = {
              id: parseInt(userId) || 0, // 使用用户实际ID
              age: parseInt(healthData.value.age) || 0,
              gender: parseInt(healthData.value.gender) || 0,
              height: parseInt(healthData.value.height) || 0,
              weight: parseFloat(healthData.value.weight) || 0,
              ap_hi: parseInt(healthData.value.apHi) || 0,
              ap_lo: parseInt(healthData.value.apLo) || 0,
              cholesterol: parseInt(healthData.value.cholesterol) || 0,
              gluc: parseInt(healthData.value.gluc) || 0,
              smoke: parseInt(healthData.value.smoke) || 0,
              alco: parseInt(healthData.value.alco) || 0,
              active: parseInt(healthData.value.active) || 0,
              cardio: parseInt(healthData.value.cardio) || 0,
              BMI: parseFloat(calculatedBMI.value) || 0
            };
            
            // 详细检查每个字段
            console.log('发送到FastAPI的数据详情:');
            Object.entries(fastApiData).forEach(([key, value]) => {
              console.log(`${key}: ${value} (类型: ${typeof value}, 是数字: ${!isNaN(value)})`);
            });
            
            // 打印诊断信息：检查是否有缺失或无效的必需字段
            console.log('===== 数据有效性诊断 =====');
            const requiredFields = ['age', 'gender', 'height', 'weight', 'ap_hi', 'ap_lo', 'cholesterol', 'gluc', 'smoke', 'alco', 'active', 'cardio'];
            requiredFields.forEach(field => {
              if (!fastApiData.hasOwnProperty(field) || fastApiData[field] === null || fastApiData[field] === undefined || isNaN(fastApiData[field])) {
                console.warn(`⚠️  必需字段 ${field} 可能有问题:`, fastApiData[field]);
              } else {
                console.log(`✅  字段 ${field} 有效:`, fastApiData[field]);
              }
            });
            
            // 检查血压值范围是否合理
            if (fastApiData.ap_hi <= fastApiData.ap_lo) {
              console.warn('⚠️  警告：收缩压(ap_hi)应大于舒张压(ap_lo)');
            }
            
            console.log('发送到FastAPI的完整数据:', fastApiData);
            
            console.log('开始发送预测请求...');
            // 注意：FastAPI期望接收列表格式的输入，需要将对象包装在数组中
            const predictionResponse = await fastApi.post('/predict', [fastApiData]);
            console.log('FastAPI预测结果:', predictionResponse.data);
            
            // 3. 将预测结果存储到localStorage，供预测结果页面使用
            localStorage.setItem('latestPrediction', JSON.stringify(predictionResponse.data));
            
            // 4. 尝试将预测结果同步到Windows数据库
            try {
              const syncResult = await syncPredictionToWindowsDB(userId, predictionResponse.data);
              if (syncResult.success !== false) {
                console.log('预测结果已同步到Windows数据库');
              } else {
                console.log('预测结果同步失败但已备份，稍后将重试');
              }
            } catch (syncError) {
              console.error('预测结果同步失败:', syncError);
              // 即使发生异常，流程也会继续
            }
            
            alert('健康数据提交成功！预测已完成');
            router.push('/user/predictions');
          } catch (predictionError) {
            console.error('预测请求失败 - 错误类型:', predictionError.name);
            console.error('预测请求失败 - 错误信息:', predictionError.message);
            
            // 详细打印错误信息，包括响应体
            if (predictionError.response) {
              console.error('响应状态:', predictionError.response.status);
              console.error('响应状态文本:', predictionError.response.statusText);
              console.error('响应数据:', JSON.stringify(predictionError.response.data, null, 2));
            } else if (predictionError.request) {
              console.error('请求已发送但没有收到响应:', predictionError.request);
            } else {
              console.error('请求配置错误:', predictionError.message);
            }
            
            // 即使预测失败，也继续流程
            alert('健康数据提交成功！预测服务暂时不可用');
            router.push('/user/predictions');
          }
        } else {
          alert('提交失败，请检查数据后重试')
        }
      } catch (error) {
        console.error('数据提交错误：', error)
        alert('提交失败，请稍后重试')
      } finally {
        isSubmitting.value = false
      }
    }

    return {
      healthData,
      calculatedBMI,
      bmiCategory,
      ageGroup,
      showCalculatedInfo,
      ageError,
      heightError,
      weightError,
      apHiError,
      apLoError,
      isSubmitting,
      handleSubmit
    }
  }
}
</script>

<style scoped>
/* 整体容器样式 */
.health-data-form {
  background-color: #f8f9fa;
  border-radius: 12px;
  padding: 30px;
  max-width: 1400px;
  margin: 30px auto;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
}

/* 标题样式 */
.health-data-form h2 {
  color: #2d3436;
  margin-bottom: 30px;
  font-size: 24px;
  font-weight: 600;
  text-align: center;
  padding-bottom: 15px;
  border-bottom: 1px solid #e9ecef;
}

/* 四方格布局容器 */
.grid-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr); /* 2x2网格布局 */
  gap: 25px;
  margin-bottom: 30px;
}

/* 卡片样式 */
.form-card {
  background-color: #ffffff;
  border-radius: 10px;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.03);
  transition: all 0.3s ease;
  overflow: hidden;
}

.form-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.07);
}

/* 表单分区样式 */
.form-section {
  padding: 25px;
}

.form-section h3 {
  color: #2d3436;
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: 500;
  padding-bottom: 10px;
  border-bottom: 1px solid #f1f3f5;
  display: flex;
  align-items: center;
}

.form-section h3::before {
  content: "";
  display: inline-block;
  width: 4px;
  height: 18px;
  background-color: #409eff;
  border-radius: 2px;
  margin-right: 10px;
}

/* 表单组样式 */
.form-group {
  margin-bottom: 20px;
  position: relative;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #495057;
  font-weight: 500;
  font-size: 14px;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 11px 15px;
  border: 1px solid #ced4da;
  border-radius: 6px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.form-group input:focus,
.form-group select:focus {
  outline: none;
  border-color: #409eff;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1);
}

/* 错误提示 */
.error {
  color: #e74c3c;
  font-size: 12px;
  display: block;
  margin-top: 5px;
}

/* 计算结果区域 */
.calculated-info {
  background-color: #f8fafc;
  padding: 12px 15px;
  border-radius: 6px;
  margin-top: 10px;
  border-left: 3px solid #409eff;
}

.calculated-info p {
  margin: 6px 0;
  color: #2d3436;
  font-size: 14px;
}

/* 提交按钮区域 */
.submit-section {
  text-align: center;
  margin-top: 20px;
}

.submit-btn {
  padding: 12px 40px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.submit-btn:hover:not(:disabled) {
  background-color: #2980b9;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

.submit-btn:disabled {
  background-color: #b8c2cc;
  cursor: not-allowed;
}

/* 响应式调整 - 平板和手机 */
@media (max-width: 992px) {
  .grid-container {
    grid-template-columns: 1fr; /* 小屏幕变为单列布局 */
  }
}

@media (max-width: 576px) {
  .health-data-form {
    padding: 20px 15px;
    margin: 15px;
  }
  
  .form-section {
    padding: 20px 15px;
  }
  
  .submit-btn {
    width: 100%;
    padding: 12px;
  }
}
</style>